package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.CodeEnum;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.service.CategoryService;

import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Autowired
    DishService dishService;

    @Autowired
    SetmealService setmealService;

    @Override
    public R<Page<Category>> pageCategory(int page, int pageSize) {
        //构造分页构造器
        Page<Category> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        //排序条件
        queryWrapper.orderByAsc("sort");
        //执行查询
        categoryMapper.selectPage(pageInfo, queryWrapper);
        return R.success(pageInfo);
    }


    @Override
    public int saveCategory(Category category) {

        //保存的分类已经存在就不再保存了
        Category hasCate = categoryMapper.selectByName(category.getName());
        if (hasCate != null) {
            return CodeEnum.ERROR_HASENTITY;
        }
        categoryMapper.insert(category);
        return CodeEnum.SUCCESS;
    }

    @Override
    public int deleteCategoryByIds(Long ids) {
        if (categoryMapper.selectById(ids) == null) {
            return CodeEnum.ENTITY_IS_DELETE;
        }
        //查询是否有套餐关联的所属分类
        if (setmealService.hasCateId(ids)) {
            return CodeEnum.ERROR_HASENTITY;
        }
        //查询是否有菜品关联的所属分类
        if (dishService.hasCateId(ids)) {
            return CodeEnum.ERROR_HASENTITY;
        }
        categoryMapper.deleteById(ids);
        return CodeEnum.SUCCESS;
    }

    @Override
    public void updateCategoryById(Category category) {
        categoryMapper.updateById(category);
    }

    @Override
    public R<List<Category>> getCategoryList(Integer type) {
        QueryWrapper<Category> queryWrapper = new QueryWrapper<>();
        if (type == null) {
            return R.success(categoryMapper.selectList(new QueryWrapper<>()));
        }
        queryWrapper.eq("type", type);
        return R.success(categoryMapper.selectList(queryWrapper));
    }
}
